<template>
	<view class="safe_tips">
		<van-notice-bar left-icon="info-o" wrapable text="点击查看安全生产报告单帮助文档" @click="goHelp" />
		<view class="form-list">
			<view class="form-item">
				<view class="form-label form-label-required">
					工程地点
				</view>
				<view class="form-value">
					<!-- <p v-if="form.address" class="form-input item-input" @click="toSelectAddress">
						{{ form.address ? form.address : "请选择工程地点" }}
					</p> -->
					<textarea class="form-input item-input" auto-height :value="form.address" disabled
						placeholder="请选择工程地点" @click="toSelectAddress" />
					<van-button v-if="pageType < 1" size="mini" style="margin-left: 32rpx;" @click="toSelectAddress">
						选择
					</van-button>
				</view>
			</view>

			<view class="form-item">
				<view class="form-label">
					房屋经纬度
				</view>
				<view class="form-value">
					<van-checkbox icon-size="28rpx" :value="posFlag" shape="square" @change="onPosFlagChange">
						是否更新
					</van-checkbox>
				</view>
			</view>

<!-- 			<view class="form-item" v-if="posFlag">
				<view class="form-label form-label-required">
					经度
				</view>
				<view class="form-value">
					<input v-model="form.posY" class="form-input" disabled />
				</view>
			</view>

			<view class="form-item" v-if="posFlag">
				<view class="form-label form-label-required">
					纬度
				</view>
				<view class="form-value">
					<input v-model="form.posX" class="form-input" disabled />
				</view>
			</view> -->

			<view class="form-item">
				<view class="form-label form-label-required">
					工程名称
				</view>
				<view class="form-value">
					<input v-model="form.proName" class="form-input" />
				</view>
			</view>

			<view class="form-item">
				<view class="form-label form-label-required">
					建设方
				</view>
				<view class="form-value">
					<input v-model="form.builder" class="form-input" />
				</view>
			</view>

			<view class="form-item">
				<view class="form-label form-label-required">
					施工方
				</view>
				<view class="form-value">
					<input v-model="form.worker" class="form-input" />
				</view>
			</view>

			<view class="form-item">
				<view class="form-label form-label-required">
					现场图片上传
				</view>
				<view class="form-value">
					<van-uploader :deletable="true" :file-list="form.docsList" :disabled="pageType > 0"
						@delete="deletePic" @after-read="afterDocRead" />
				</view>
			</view>

			<view class="form-item">
				<view class="form-label">
					备注
				</view>
				<view class="form-value">
					<textarea v-model="form.memo" style="height: 150rpx;" class="form-input form-textarea" />
				</view>
			</view>

			<view class="form-item">
				<view class="form-label">
					发放日期
				</view>
				<view class="form-value">
					<input disabled @click="openTimePicker" v-model="form.createTime" class="form-input" />
					<van-popup :show="showTimePicker" position="bottom" custom-style="height: 40%;"
						@close="onTimePickerClose">
						<van-datetime-picker type="date" :min-date="minDate" :formatter="formatter"
							@confirm="confirmDate" />
					</van-popup>
				</view>
			</view>

			<view class="form-item">
				<view class="form-label">
					发放部门
				</view>
				<view class="form-value">
					<input disabled v-model="form.creater" class="form-input" />
				</view>
			</view>

			<view class="form-item">
				<view class="form-label">
					建设方签名
				</view>
				<view class="form-value">
					<image @click="toSign" :src="localSignPic" style="height: 150rpx;width: 50%;" class="form-input">
					</image>
				</view>
			</view>

			<view v-if="pageType < 1" class="form-item">
				<van-button size="small" type="info" @click="handleSubmit">
					提交
				</van-button>
			</view>

		</view>
	</view>
</template>

<script>
	import {
		saveNotify,
		getNotifyById
	} from '@/request/api.js'
	export default {
		data() {
			return {
				detailId: -1,
				pageType: 0, // 0 新增 1查看
				currentDate: new Date().getTime(),
				minDate: new Date().getTime(),
				posFlag: false,
				formatter: (type, value) => {
					if (type === 'year') {
						return `${value}年`
					}
					if (type === 'month') {
						return `${value}月`
					}
					return `${value}日`
				},
				localSignPic: null,
				showTimePicker: false,
				form: {
					createTime: '',
					houseID: '', // 房屋编号
					address: '', // 工程地点
					proName: '', // 工程名称
					builder: '', // 建设方
					worker: '', // 施工方
					sign: '', // 建设方签名图片地址
					memo: '', // 备注
					creater: '', // 当前用户姓名,
					userID: '', // 当前用户账号
					docsList: [] // 现场图片列表
				}
			};
		},
		onLoad(e) {
			this.init()
			this.pageType = e.pageType
			if (this.pageType > 0) {
				this.detailId = e.detailId
				this.getDetail()
			} else {
				var aData = new Date()
				var month = aData.getMonth() < 9 ? "0" + (aData.getMonth() + 1) : aData.getMonth() + 1;
				var date = aData.getDate() <= 9 ? "0" + aData.getDate() : aData.getDate();
				this.value = aData.getFullYear() + "-" + month + "-" + date;
				this.form.createTime = aData.getFullYear() + "/" + month + "/" + date;
			}
		},
		methods: {
			onPosFlagChange(e) {
				if (e.detail) {
					uni.getLocation({
						type: 'wgs84',
						success: (res) => {
							this.$set(this.form, 'posX', res.longitude)
							this.$set(this.form, 'posY', res.latitude)
						}
					})
				}
				this.posFlag = e.detail
			},
			deletePic(index) {
				this.form.docsList.splice(index, 1)
			},
			goHelp() {
				uni.downloadFile({
					url: this.$config.baseUrl + '/help/gzs.doc',
					success: (res) => {
						uni.showToast({
							title: '正在打开帮助文档'
						})
						var filePath = res.tempFilePath;
						uni.openDocument({
							filePath: filePath,
							showMenu: true,
							success: function(res) {
								console.log('打开文档成功');
							}
						});
					},
					fail: () => {
						uni.showToast({
							icon: 'none',
							title: '文件下载失败'
						})
					}
				})
			},
			getDetail() {
				getNotifyById({
					Id: this.detailId
				}).then(res => {
					this.form = {
						...this.form,
						...res.data[0]
					}
					this.localSignPic = this.form.sign

					this.form.createTime = this.form.createTime.substring(0, 10).replaceAll('-', '/');

					for (let docIndex = 0; docIndex < this.form.docsList.length; docIndex++) {
						const docItem = this.form.docsList[docIndex]
						docItem.url = docItem.path
						docItem.deletable = false
						// this.form.docsList[docIndex]['url'] = docItem.
					}
				})
			},
			afterDocRead(event) {
				const {
					file
				} = event.detail;
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				uni.uploadFile({
					url: this.$config.uploadUrl,
					filePath: file.url,
					name: 'file',
					formData: {
						filetype: "image",
					},
					success: (res) => {
						// 上传完成需要更新 fileList
						const {
							result
						} = JSON.parse(res.data)
						this.form.docsList.push({
							...file,
							url: result,
							deletable: true
						});
					},
				});
			},
			confirmDate(e) {
				var aData = new Date(parseInt(e.detail))
				var month = aData.getMonth() < 9 ? "0" + (aData.getMonth() + 1) : aData.getMonth() + 1;
				var date = aData.getDate() <= 9 ? "0" + aData.getDate() : aData.getDate();
				this.value = aData.getFullYear() + "-" + month + "-" + date;
				this.form.createTime = aData.getFullYear() + "/" + month + "/" + date;
				this.showTimePicker = false
			},
			openTimePicker() {
				this.showTimePicker = true
			},
			onTimePickerClose() {
				this.showTimePicker = false
			},
			init() {
				uni.getStorage({
					key: 'userInfo',
					success: (res) => {
						const data = res.data
						// account: "admin"
						// deptName: "湖圩村"
						// password: "admin"
						// userName: "建设管理科"
						this.form.userID = data[0].account
						this.form.creater = data[0].deptName
					}
				})
			},
			toSelectAddress() {
				if (this.pageType < 1) {
					uni.$on('handleSelectAddress', (item) => {
						this.form.address = item.address // 工程地点
						this.form.houseID = item.houseID // 房屋id
					})
					uni.navigateTo({
						url: '../select_project_address/select_project_address?pageType=0&needSheQu=false'
					})
				}
			},
			handleSubmit() {
				const values = Object.values(this.form)
				const keys = Object.keys(this.form)
				let requiredFlag = true
				for (let valueIndex = 0; valueIndex < values.length; valueIndex++) {
					const valueItem = values[valueIndex]
					const keyItem = keys[valueIndex]
					if (keyItem === 'memo') continue // 跳过，不必填
					if (keyItem === 'sign') continue // 跳过，不必填
					if (keyItem === 'creater') continue // 跳过，不必填
					if (keyItem === 'createTime') continue // 跳过，不必填
					if (keyItem === 'posY') continue // 跳过，不必填
					if (keyItem === 'posX') continue // 跳过，不必填
					const itemlength = (typeof valueItem === 'number') ? valueItem : valueItem.length
					if (itemlength <= 0) {
						requiredFlag = false
						break
					}
					// console.log(valueItem, (typeof valueItem === 'number') ? valueItem : valueItem.length)
				}
				if (!requiredFlag) {
					uni.showToast({
						icon: 'none',
						title: '请完成所有必填项后再提交'
					})
					return
				}
				for (let docsIndex = 0; docsIndex < this.form.docsList.length; docsIndex++) {
					// 处理问题字段
					const docsItem = this.form.docsList[docsIndex]
					const tempItemObj = {}
					tempItemObj['name'] = docsItem.url
					tempItemObj['path'] = docsItem.url
					this.form.docsList[docsIndex] = tempItemObj
				}
				saveNotify(this.form).then(res => {
					uni.$emit('refreshTips')
					uni.navigateBack({
						delta: 1
					})
				})
			},
			saveSign(data) {
				console.log(data)
			},
			toSign() {
				uni.$on('handleSaveSign', ({
					tempPath
				}) => {
					console.log('收到了更新', tempPath)
					// this.signPic = tempPath
					this.localSignPic = tempPath
					uni.showLoading({
						title: '正在上传签名'
					})
					uni.uploadFile({
						url: this.$config.uploadUrl,
						filePath: tempPath,
						name: "file",
						formData: {
							filetype: "image",
						},
						success: (res) => {
							uni.hideLoading()
							const {
								result
							} = JSON.parse(res.data) // result就是后端返回的图片地址
							this.form.sign = result // 把图片地址复制到form里面
						},
						fail: (e) => {
							uni.hideLoading()
							uni.showToast({
								icon: 'none',
								title: '签名上传失败'
							})
						}
					})
				})
				uni.navigateTo({
					url: '../sign_page/sign_page?callback=handleSaveSign'
				})
			}
		}
	}
</script>

<style lang="scss">
	.safe_tips {
		.form-list {
			padding: 32rpx;
			box-sizing: border-box;

			.form-item {
				display: flex;
				align-items: flex-start;
				justify-content: center;
				margin-bottom: 32rpx;

				.form-label {
					width: 150rpx;
					margin-right: 32rpx;
					font-size: 28rpx;
					color: #141414;
				}

				.form-label-required {
					&::before {
						content: "*";
						color: red;
						margin-right: 6rpx;
					}
				}

				.form-value {
					font-size: 28rpx;
					color: #141414;
					flex: 1;
					width: 0;
					display: flex;
					align-items: center;

					.form-textarea {
						padding: 16rpx 0;
					}

					.form-input {
						padding: 0 16rpx;
						box-sizing: border-box;
						border: 1px solid #CECECE;
					}
				}
			}
		}
	}
</style>
